package com.dymedia.aibo.mvp.ui.widget;

import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.VideoView;

public class MyVideoView extends VideoView {
    ProgressBar mProgressBar;
    Handler mHandler = new Handler();

    public MyVideoView(Context context) {
        super(context);
        init();
    }
    public MyVideoView(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        init();
    }

    public void setProgressBar(ProgressBar p){
        mProgressBar = p;
    }

    public void showProgressBar(){
        mHandler.removeCallbacksAndMessages(null);
        mHandler.post(() -> mProgressBar.setVisibility(View.VISIBLE));
    }

    public void hideProgressBar(){
        mHandler.removeCallbacksAndMessages(null);
        mHandler.post(() -> mProgressBar.setVisibility(View.GONE));
    }

    private void init(){
        setFocusable(false);
        setOnInfoListener((mp, what, extra) -> {
            switch (what){
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                    showProgressBar();
                    //mHandler.postDelayed(() -> hideProgressBar(), 10000);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    hideProgressBar();
                    break;
            }
            return false;
        });
    }

    public void stop() {
        stopPlayback();
        setBackgroundColor(Color.BLACK);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }
}
